//
//  SucursalesDao.m
//  Megatlon
//
//  Created by Leandro Milmanda on 5/7/12.
//  Copyright 2012 www.lemil.com.ar. All rights reserved.
//


#import "SucursalesDao.h"
#import "JSON.h"

#define kiMegatlonServiceUrl @"http://www.lemil.com.ar/apps/imegatlon/sucursales"
//#define kiMegatlonServiceUrl @"http://localhost:10088/imegatlon/sucursales"

@implementation SucursalesDao 

//pragma - Class Methods

static SucursalesDao *gInstance = NULL;
    
+ (SucursalesDao *)instance
{
    @synchronized(self)
    {
        if (gInstance == NULL)
            gInstance = [[self alloc] init];
    }
    
    return(gInstance);
}



//pragma - Instance Methods

- (id)init
{
    self = [super init];
    if (self) {
        loaded = NO;
    }
    return self;
}

-(void) dealloc 
{
    [jsonObject release];
    [jsonString release];
    [jsonObjectGrilla release];
    [super dealloc];
    
}

//This method loads the information fron the web and caches it locally
-(void)load {
   
    @try {
        NSData *dataReply = nil;
        NSURLRequest *request = nil;
        NSURLResponse *response = nil;
        NSError *error = nil;
                
        NSString *surl = [kiMegatlonServiceUrl stringByAppendingFormat:@"?dgid=%@", [[UIDevice currentDevice] uniqueGlobalDeviceIdentifier] ];
        
        
        NSLog(surl);
        
        request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: surl]];  
        [request setHTTPMethod: @"GET"];  
        [request setHTTPBody: [[NSString stringWithString:@""] dataUsingEncoding: NSUTF8StringEncoding]];  
        
        dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];  
        
        jsonString = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];  
        
        jsonString =  [[self parseString: jsonString] copy];
        
        jsonObject = [[jsonString JSONValue] copy];
        
        NSArray *todasLasGrillas = [(NSDictionary*)jsonObject objectForKey:@"grillaHoraria"];
        jsonObjectGrilla = [(NSDictionary*)todasLasGrillas objectAtIndex:0];

        loaded = YES;
    } 
    @catch (NSException * ex) {
        NSLog(@"doSomethingFancy failed: %@",ex);
    }
       
}


-(BOOL)isLoaded {
    return loaded;
}

-(NSDictionary *)getByIndex:(int)index {
    
    NSArray* todasLasSucursales = [(NSDictionary*)jsonObject objectForKey:@"sucursales"];
    
    NSDictionary* unaSucursal = [todasLasSucursales objectAtIndex:index];
    
    return unaSucursal;

}


-(NSArray *)getAll 
{
    return[(NSDictionary*)[jsonString JSONValue] objectForKey:@"sucursales"];
}

-(int)getTotalSucursales
{
    return [[self getAll] count];
}

-(NSString *)parseString:(NSString *)input
{
    NSString* output = input;
    output = [output stringByReplacingOccurrencesOfString: @"&amp;" withString: @"&"];
    output = [output stringByReplacingOccurrencesOfString: @"&AMP;" withString: @"&"];
    
    return output;
}


-(BOOL)isOpenedSucursalId:(int)someSucursalId atDayNumber:(int)dayNumber andTime:(int)hour andMinutes:(int)mins
{
    BOOL retval = NO;
  
    NSDictionary *todasLasGrillasDictionary = jsonObjectGrilla;
    
    NSString *sucid = [NSString stringWithFormat:@"s=%d", someSucursalId];
    NSString *diaid = [NSString stringWithFormat:@"d=%d", dayNumber];
    
    NSDictionary* grillaSucursal = [todasLasGrillasDictionary objectForKey:sucid]; 
    NSDictionary *grillaSucursalDelDia = [grillaSucursal objectForKey:diaid];
    
    NSString *desde = [grillaSucursalDelDia objectForKey:@"d"];
    NSString *hasta = [grillaSucursalDelDia objectForKey:@"h"];
    
    
    NSArray *ardesde = [desde componentsSeparatedByString:@":"] ;
    NSArray *arhasta = [hasta componentsSeparatedByString:@":"] ;                        
    
    int horaDesde       = [[ardesde objectAtIndex:0] intValue];
    int minutosDesde    = [[ardesde objectAtIndex:1] intValue]; 
    int horaHasta       = [[arhasta objectAtIndex:0] intValue]; 
    int minutosHasta    = [[arhasta objectAtIndex:1] intValue]; 
    
    int desdemin = ( horaDesde * 100 ) + minutosDesde;
    int hastamin = ( horaHasta * 100 ) + minutosHasta;
    
    int horamin = ( hour * 100 ) + mins;
    
    if(horamin < desdemin ) {
        retval = NO;
    } else if ( horamin > hastamin ) {
        retval = NO;
    } else {
        retval = YES;
    }
    
    return retval;
}




@end
